
import { baseURL } from '../env'
/**
 *  使用Promise 对wx.request进行分装
 * @param {*} params 
 */
function request(params = { url, method, data }) {
	return  new Promise(function (resolve,reject) {
		let header = { 
			'Content-Type': 'application/json',
			'Authorization': wx.getStorageSync('token')
		}
		wx.request({
			url: baseURL + params.url,
			method: params.method,
			data: params.data,
			header: header,
			timeout: 5000,
			success(res) { 
				if (res.statusCode == 200) {
					if (res.data.code == 200) {
						resolve(res.data);
					} else if(res.data.code == 401) {//因为token失效
						wx.setStorageSync('isLogin',false);
						wx.showToast({
							title: '请先登录!',
							icon: 'none'
						})
						wx.navigateTo({
							url: '/pages/component/mine/account/login/index',
						})
					} else if(res.data.code == 500) {
						wx.showToast({
							title: res.data.message,
							icon: 'none'
						})
						reject(res.data);
					}else{
						wx.showToast({
							title: '提示',
							content: res.data.message,
							showCancel: false,
							success:function(res) {}
						})
						reject(res.data);
					}
				} else {
					wx.showToast({
						title: '提示',
						content: '网络请求超时！',
						showCancel: false,
						success: function(res) {}
					})
					reject();
				}
			},
			fail (err) {
				reject(err)
			}
		})
	})
}

module.exports = {
  request: request
}
